package com.haima.sage.bigdata.api.common;

public class HexUtils {
    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String bytesToHex(byte[] bytes) {
        char[] chars = new char[bytes.length * 2];
        for (int i = 0; i < chars.length; i = i + 2) {
            byte b = bytes[i / 2];
            chars[i] = HEX_CHAR[(b >>> 0x4) & 0xf];
            chars[i + 1] = HEX_CHAR[b & 0xf];
        }
        return new String(chars);
    }

    public static byte[] hexToBytes(String hexString) {
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static void main(String[] args) throws Exception {
        long l1 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            hexToBytes("0123456789ABCDEF");
        }
        long l2 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            hexToBytes("0123456789ABCDEF");
        }
        long l3 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            hexToBytes("0123456789ABCDEF");
        }
        long l4 = System.currentTimeMillis();
        System.out.println(l2 - l1);
        System.out.println(l3 - l2);
        System.out.println(l4 - l3);
    }
}
